package com.salesmanager.core.utils.encrypt;

        import java.security.MessageDigest;
        import java.security.NoSuchAlgorithmException;
        import java.util.Iterator;
        import java.util.Map;
        import java.util.Set;
        import java.util.SortedMap;
        import java.util.TreeMap;

        import org.slf4j.LoggerFactory;

public class EncryptionUtil {
    public final static String ENCODER_SHA1 = "SHA-1";
    public final static String ENCODER_MD5 = "MD5";

    public final static String DEFAULT_CHARSET = "utf-8";

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance(ENCODER_MD5);
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(ENCODER_SHA1);
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String getsign(SortedMap<Object, String>  sParams, String key) {
        Set es = sParams.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        StringBuilder sb = new StringBuilder();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key.trim() + "");
        String signkey = sb.toString();

        LoggerFactory.getLogger(EncryptionUtil.class).error("before MD5 :"+signkey);
        String sign = MD5(signkey, "utf-8");

        return sign;
    }
    public static String combineStr(SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }

        String signstring = sb.toString();
        signstring = signstring.substring(0, signstring.length()-1);
        return signstring;
    }
    public static String createSign(SortedMap<Object,Object> parameters, String encoder){
        String combineStr = combineStr(parameters);
        if (encoder.equals(ENCODER_SHA1))
            return SHA1(combineStr);
        else if (encoder.equals(ENCODER_MD5))
            return MD5(combineStr, DEFAULT_CHARSET);
        return null;
    }

    public static void main(String[] args) {
//    	timestamp: '1435766887',
//    	nonceStr: 'noncestr',
//    	signature: 'c702ec23a0cba78401e794625e698fb0f0b4125a',

        String noncestr = "noncestr";
        String jsapi_ticket = "bxLdikRXVbTPdHSM05e5uzK9vV0d6-JDqE-Skutoy92Uy3gcfzGel58Zk5EgJuJ0MAVbDyHou5MyHMXRpqvzfA";
        String c_timestamp = String.valueOf(System.currentTimeMillis()/1000);
        System.out.println(c_timestamp);
        String url = "http://49.73.1.218:9999/shop/mobile/test";

        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        parameters.put("noncestr", noncestr);
        parameters.put("jsapi_ticket", jsapi_ticket);
        parameters.put("timestamp", c_timestamp);
        parameters.put("url", url);

//    	  String test = "jsapi_ticket=bxLdikRXVbTPdHSM05e5uzK9vV0d6-JDqE-Skutoy92Uy3gcfzGel58Zk5EgJuJ0MAVbDyHou5MyHMXRpqvzfA&noncestr=noncestr&timestamp=1435766506&url=http://49.73.1.218:9999/shop/mobile/test";
        //30bbeffb239a77bb79562d1d2461fb31a0b07cdf
//          System.out.println(SHA1(test));
//          System.out.println(createSign(parameters, ENCODER_SHA1));
        System.out.println(createSign(parameters, ENCODER_MD5));
    }
}
